package com.my.financial.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Component;

import com.my.financial.controller.form.AddForm;
import com.my.financial.domain.User;

@Component
public class FinancialDao {
	private NamedParameterJdbcTemplate npJdbcTemplate;
	
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.npJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}
	
	public void save(AddForm addForm){
		String sql = "insert into financialplan(createTime,type,item,amount,user,summary) "
				+ "values(:createTime,:type,:item,:amount,:user,:summary)";
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(addForm);
		npJdbcTemplate.update(sql, paramSource);
	}
	
	public List<Map<String, Object>> viewListItem(String sql){
		return npJdbcTemplate.getJdbcOperations().queryForList(sql);
	}
	
	@SuppressWarnings("deprecation")
	public int countAllItem(String sql) {
		return npJdbcTemplate.getJdbcOperations().queryForInt(sql);
	}
	
	public User findByUserNameAndPassword(String userName, String password) {
		String sql = "select * from user1 where username=:username and password=:password";
		HashMap<String, String> map = new HashMap<>();
		map.put("username", userName);
		map.put("password", password);
		try {
			return npJdbcTemplate.queryForObject(sql, map,
					ParameterizedBeanPropertyRowMapper.newInstance(User.class));
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
}
